import json
import os
from shapely.geometry import Polygon

obj_dir = "./json_dir/"
name_list = os.listdir(obj_dir)
for name1 in name_list:
    if name1.split(".")[1] == "json":
        img_path = obj_dir + name1.split(".")[0] + ".jpg"
        json_path = obj_dir + name1.split(".")[0] + ".json"
        txt_path = obj_dir + name1.split(".")[0] + ".txt"

        row_list = []
        with open(json_path) as f:
            dict1 = json.load(f)
            imageWidth = dict1["imageWidth"]
            imageHeight = dict1["imageHeight"]
            img_name = dict1["imagePath"]
            shapes = dict1["shapes"]

            images_points = [
                (0, 0),
                (imageWidth, 0),
                (imageWidth, imageHeight),
                (0, imageHeight),
            ]
            images_quad = Polygon(images_points)

            for shape in shapes:
                if shape["label"] == "WHITE_LABEL":
                    quad2 = Polygon(shape["points"])
                    intersection = images_quad.intersection(quad2)
                    intersection_points = (
                        list(intersection.exterior.coords)
                        if not intersection.is_empty
                        else []
                    )
                    if len(intersection_points) != 0:
                        row1 = [
                            0,
                            intersection_points[0][0] / imageWidth,
                            intersection_points[0][1] / imageHeight,
                            intersection_points[1][0] / imageWidth,
                            intersection_points[1][1] / imageHeight,
                            intersection_points[2][0] / imageWidth,
                            intersection_points[2][1] / imageHeight,
                            intersection_points[3][0] / imageWidth,
                            intersection_points[3][1] / imageHeight,
                        ]
                        row1 = list(map("{:.6f}".format, row1))
                        row1[0] = 0
                        row_list.append(row1)
                    else:
                        print("No intersection points found for {}".format(img_name))

        with open(txt_path, "w", newline="") as f:
            for row in row_list:
                for data in row:
                    f.write(str(data))
                    f.write(" ")
                f.write("\r\n")
